package com.corpgovernment.organization.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.organization.enums.CardTypeEnum;
import com.corpgovernment.api.organization.enums.UserOrgRelationStatusEnum;
import com.corpgovernment.api.organization.model.orguserrelation.request.ListUserOrgRelationForLoginRequest;
import com.corpgovernment.api.organization.model.orguserrelation.response.ListUserOrgRelationForLoginResponse;
import com.corpgovernment.api.organization.model.user.employee.OrgPostLogVo;
import com.corpgovernment.api.organization.vo.TransferEmployeeOrgInfoVo;
import com.corpgovernment.api.permission.vo.GetUserRoleDetailRequest;
import com.corpgovernment.api.permission.vo.GetUserRoleListInfo;
import com.corpgovernment.api.permission.vo.GetUserRoleListResponse;
import com.corpgovernment.job.dao.entity.db.EmployeeJobRelationDo;
import com.corpgovernment.job.dao.mapper.EmployeeJobRelationMapper;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.EmployeeOperateEnum;
import com.corpgovernment.organization.dataloader.ApprovalClientLoader;
import com.corpgovernment.organization.dataloader.db.OrganizationChangeHistoryLoader;
import com.corpgovernment.organization.dto.ListEmployeeQuery;
import com.corpgovernment.organization.dto.OrgUserInfoPk;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.entity.db.MbPostInfo;
import com.corpgovernment.organization.entity.db.MbUserOrgRelation;
import com.corpgovernment.organization.enumm.CardCodeEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.mapper.MbOrgEmployeeMapper;
import com.corpgovernment.organization.mapper.MbOrgUserIdcardMapper;
import com.corpgovernment.organization.mapper.MbUserLoginMapper;
import com.corpgovernment.organization.mapper.MbUserOrgRelationMapper;
import com.corpgovernment.organization.model.OrganizationChangeHistoryModel;
import com.corpgovernment.organization.service.BookingRelationService;
import com.corpgovernment.organization.service.IFreshPassengerService;
import com.corpgovernment.organization.service.IOrgUserIdCardService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.IOrganizationUserFfpService;
import com.corpgovernment.organization.service.IPostService;
import com.corpgovernment.organization.service.IUserOrgRelationService;
import com.corpgovernment.organization.service.OrgPostLogService;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.corpgovernment.permission.entity.db.MbUserRole;
import com.corpgovernment.permission.mapper.UserRoleMapper;
import com.corpgovernment.permission.service.UserService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.corpgovernment.organization.controller.OrganizationEmployeeController.idMask;

/**
 * @author wangyujue
 */
@Service
@Slf4j
public class UserOrgRelationServiceImpl extends OrgPostLogService implements IUserOrgRelationService {

    @Autowired
    private MbUserOrgRelationMapper mbUserOrgRelationMapper;
    @Autowired
    private OrganizationEmployeeServiceImpl organizationEmployeeService;
    @Autowired
    private IOrgUserIdCardService organizationUserIdCardService;
    @Autowired
    private UserService userService;
    @Autowired
    private IPostService postService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private MbOrgEmployeeMapper orgEmployeeMapper;
    @Autowired
    private MbOrgUserIdcardMapper orgUserIdcardMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private MbUserLoginMapper userLoginMapper;
    @Autowired
    private IOrganizationUserFfpService organizationUserFfpService;
    @Autowired
    private IFreshPassengerService freshPassengerService;
    @Autowired
    private FreshPassengerRelationServiceImpl freshPassengerRelationService;
    @Autowired
    private BookingRelationService bookingRelationService;
    @Autowired
    private ApprovalClientLoader approvalClientLoader;
    @Autowired
    private OrganizationChangeHistoryLoader organizationChangeHistoryLoader;
    @Resource
    private EmployeeJobRelationMapper employeeJobRelationMapper;


    /**
     * 证件号掩码加密
     *
     * @param cardNo   证件号
     * @param cardType 证件类型
     * @return
     */
    private static String encryptCardNo(String cardNo, Integer cardType) {
        if (cardType == null || StrUtil.isEmpty(cardNo)) {
            return null;
        }
        if (cardType.equals(CardTypeEnum.ID_CARD.getCode())) {
            return idMask(cardNo, 4, 3);
        }
        if (cardNo.length() < 3) {
            return cardNo;
        }
        return idMask(cardNo, new BigDecimal(cardNo.length()).divide(new BigDecimal(3), 0, BigDecimal.ROUND_HALF_UP).intValue(), 2);
    }

    @Override
    public List<MbOrgEmployeeInfo> listByQuery(ListEmployeeQuery listEmployeeQuery, Long roleId) {
        String orgId = listEmployeeQuery.getOrgId();
        String query = listEmployeeQuery.getQuery();
        List<String> uids = new ArrayList<>();
        if (StringUtils.isNotBlank(query)) {
            uids = listByQuery(query);
        }
        if (Objects.nonNull(listEmployeeQuery.getPageNum()) && Objects.nonNull(listEmployeeQuery.getPageSize())) {
            PageContext.startPage(listEmployeeQuery.getPageNum(), listEmployeeQuery.getPageSize());
        }
        return orgEmployeeMapper.listByQueryAndOgrIds(uids, Lists.newArrayList(orgId), roleId);
    }

    @Override
    public IPage<MbOrgEmployeeInfo> listByQueryPage(ListEmployeeQuery listEmployeeQuery, Long roleId, Long jobId) {
        String orgId = listEmployeeQuery.getOrgId();
        String query = listEmployeeQuery.getQuery();
        List<String> uids = new ArrayList<>();
        if (StringUtils.isNotBlank(query)) {
            uids = listByQuery(query);
        }
        IPage<MbOrgEmployeeInfo> objectIPage = PageContext.startPage(listEmployeeQuery.getPageNum(), listEmployeeQuery.getPageSize());

        List<String> filterUid = filterByJob(jobId, uids);
        // 如果岗位为空，直接返回
        if (jobId != null && CollectionUtils.isEmpty(filterUid)) {
            return objectIPage;
        }

        List<MbOrgEmployeeInfo> mbOrgEmployeeInfos = orgEmployeeMapper.listByQueryAndOgrIds(filterUid, Optional.ofNullable(orgId).map(Lists::newArrayList).orElse(null) , roleId);
        return objectIPage.setRecords(mbOrgEmployeeInfos);
    }


    /**
     * 根据岗位过滤uid
     */
    private List<String> filterByJob(Long jobId, List<String> uids) {
        if (jobId == null) {
            return uids;
        }


        // 获取传入岗位下的员工
        List<String> employeeIdByJobId = employeeJobRelationMapper.listByJobIdList(Lists.newArrayList(jobId)).stream()
                .map(EmployeeJobRelationDo::getUid)
                .collect(Collectors.toList());

        // 如果传入uid为空，直接返回岗位下的员工
        if (CollectionUtils.isEmpty(uids)) {
            return employeeIdByJobId;
        }


        // 交集
        return uids.stream().filter(employeeIdByJobId::contains).collect(Collectors.toList());
    }

    @Override
    public List<MbOrgEmployeeInfo> listByQueryAndOgrIds(ListEmployeeQuery listEmployeeQuery, List<String> orgIds, Long roleId) {
        String query = listEmployeeQuery.getQuery();
        List<String> uids = new ArrayList<>();
        if (StringUtils.isNotBlank(query)) {
            uids = listByQuery(query);
            log.info("根据query查询出得uid:{}", JsonUtils.toJsonString(uids));
            if (CollectionUtils.isEmpty(uids)) {
                return new ArrayList<>();
            }
        }

        if (Objects.nonNull(listEmployeeQuery.getPageNum()) && Objects.nonNull(listEmployeeQuery.getPageSize())) {
            PageContext.startPage(listEmployeeQuery.getPageNum(), listEmployeeQuery.getPageSize());
        }
        return orgEmployeeMapper.listByQueryAndOgrIds(uids, orgIds, roleId);
    }

    @Override
    public IPage<MbOrgEmployeeInfo> listByQueryAndOgrIdsPage(ListEmployeeQuery listEmployeeQuery, List<String> orgIds, Long roleId, Long jobId) {
        String query = listEmployeeQuery.getQuery();
        List<String> uids = new ArrayList<>();
        if (StringUtils.isNotBlank(query)) {
            uids = listByQuery(query);
            log.info("根据query查询出得uid:{}", JsonUtils.toJsonString(uids));
            if (CollectionUtils.isEmpty(uids)) {
                return new Page<>();
            }
        }

        IPage<MbOrgEmployeeInfo> objectIPage = PageContext.startPage(listEmployeeQuery.getPageNum(), listEmployeeQuery.getPageSize());

        List<String> filterUid = filterByJob(jobId, uids);
        // 如果岗位为空，直接返回
        if (jobId != null && CollectionUtils.isEmpty(filterUid)) {
            return objectIPage;
        }

        List<MbOrgEmployeeInfo> mbOrgEmployeeInfos = orgEmployeeMapper.listByQueryAndOgrIds(filterUid, orgIds, roleId);

        return objectIPage.setRecords(mbOrgEmployeeInfos);
    }

    /**
     * 根据名称or手机号码or证件号码查询
     *
     * @param query
     * @return
     */
    public List<String> listByQuery(String query) {
        List<MbOrgEmployeeInfo> orgEmployeeInfoList = orgEmployeeMapper.findAllNameAndPhone();
        List<String> uids = orgEmployeeInfoList.stream().filter(e -> StringUtils.contains(e.getName(), query) || StringUtils.contains(e.getMobilePhone(), query)).map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());
        List<MbOrgUserIdcard> orgUserIdcardList = orgUserIdcardMapper.findAllCardNo();
        uids.addAll(orgUserIdcardList.stream().filter(e -> StringUtils.contains(e.getCardNo(), query)).map(MbOrgUserIdcard::getEmployeeUid).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        return uids.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public boolean delete(String id, String orgId) {

        try {
            MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
            MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(id);
            if (mbOrgEmployeeInfo == null) {
                return false;
            }
            Long postId = mbOrgEmployeeInfo.getPostId();
            MbUserOrgRelation mbUserOrgRelation;
            ArrayList<String> list = Lists.newArrayList();
            list.add(id);
            // 查询人的证件信息
            List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(list);
            Map<String, List<MbOrgUserIdcard>> userCardMap = MapUtil.newHashMap();
            if (CollUtil.isNotEmpty(userIdcards)) {
                userCardMap = userIdcards.stream().sorted((a, b) -> b.getDatachangeLasttime().compareTo(a.getDatachangeLasttime())).collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
            }
            OrgPostLogVo orgEmployeeVo = new OrgPostLogVo();
            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
            orgEmployeeVo.setPhone("+" + mbOrgEmployeeInfo.getAreaCode() + " " + mbOrgEmployeeInfo.getMobilePhone());
            List<MbOrgUserIdcard> idcards = userCardMap.get(mbOrgEmployeeInfo.getUid());
            if (CollUtil.isNotEmpty(idcards)) {
                MbOrgUserIdcard mbOrgUserIdcard = idcards.get(0);
                CardCodeEnum cardCodeEnum = CardCodeEnum.get(String.valueOf(mbOrgUserIdcard.getCardType()));
                orgEmployeeVo.setCardType(cardCodeEnum.getDesc());
                // 证件号加密
                String encryptStr = encryptCardNo(mbOrgUserIdcard.getCardNo(), mbOrgUserIdcard.getCardType());
                orgEmployeeVo.setCardNo(encryptStr);
            }
            // 是不是管理员
            GetUserRoleDetailRequest req = new GetUserRoleDetailRequest();
            req.setUid(mbOrgEmployeeInfo.getUid());
            req.setOrgId(mbOrgEmployeeInfo.getOrgId());
            GetUserRoleListResponse data = userService.getUserRoleDetail(req);
            List<GetUserRoleListInfo> userRoleListInfoList = data.getUserRoleListInfoList();
            if (CollUtil.isNotEmpty(userRoleListInfoList)) {
                orgEmployeeVo.setIsMageger("是");
            } else {
                orgEmployeeVo.setIsMageger("否");
            }
            if (mbOrgEmployeeInfo.getIsLeader() == null || !mbOrgEmployeeInfo.getIsLeader()) {
                orgEmployeeVo.setIsCharge("否");
            } else {
                orgEmployeeVo.setIsCharge("是");
            }
            if (mbOrgInfo != null) {
                orgEmployeeVo.setCompanyName(mbOrgInfo.getName());
            }
            if (postId == null) {
                mbUserOrgRelation = new MbUserOrgRelation();
                mbUserOrgRelation.setOrgId(orgId);
                mbUserOrgRelation.setUid(id);
                List<MbUserOrgRelation> select = mbUserOrgRelationMapper.select(mbUserOrgRelation);
                // 职级
                if (!CollectionUtils.isEmpty(select)) {
                    MbUserOrgRelation mbRelation = select.get(0);
                    postId = mbRelation.getPostId();
                    if (postId != null) {
                        MbPostInfo mbPostInfo = postService.find(postId);
                        orgEmployeeVo.setRank(mbPostInfo.getName());
                    }

                }
            }

            UserOrgRelationStatusEnum byCode = UserOrgRelationStatusEnum.getByCode(mbOrgEmployeeInfo.getStatus() == null ? 1 : mbOrgEmployeeInfo.getStatus());
            orgEmployeeVo.setStatus(byCode.getDesc());

            deleteOperateLog(orgEmployeeVo, new OrgPostLogVo());
        } catch (Exception e) {
            log.error("删除人员信息操作日志失败，原因:{}", e.getMessage(), e);
        }

        int delete = mbUserOrgRelationMapper.deleteByOrgIdAndUid(id, orgId);

        return delete > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteAllByUid(String uid, String orgId) {
        log.info("uid:{},orgId:{}", uid, orgId);
        if (StringUtils.isBlank(orgId)){
            List<MbUserOrgRelation> orgRelationList = mbUserOrgRelationMapper.listByUid(uid);
            if (CollectionUtils.isNotEmpty(orgRelationList)){
                orgId = orgRelationList.get(0).getOrgId();
            }else {
                orgId = StringUtils.EMPTY;
            }
        }
        organizationChangeHistoryLoader.batchSave(Collections.singletonList(buildOrganizationChangeHistory(uid, orgId)));
        //登录信息
        userLoginMapper.deleteByUid(uid);
        //员工信息表
        organizationEmployeeService.deleteByUid(uid);
        //员工关联信息表
        mbUserOrgRelationMapper.deleteByOrgIdAndUid(uid, orgId);
        //删除证件信息
        organizationUserIdCardService.deleteByEmployeeUid(uid);
        //删除常旅客
        organizationUserFfpService.deleteByUid(uid);
        //删除用户新鲜度
        freshPassengerService.deleteEmployee(uid, null);
        //删除用户新鲜度关联表
        freshPassengerRelationService.deletedRelationByUid(uid);
        //删除代订信息
        bookingRelationService.deleteBookingRelationByUid(uid);
        //删除审批配置
        approvalClientLoader.deleteFlowTmpl(uid);
        //删除角色信息
        Example example = new Example(MbUserRole.class);
        example.createCriteria().andEqualTo("uid", uid);
        userRoleMapper.deleteByExample(example);
        //删除岗位信息
        employeeJobRelationMapper.removeByUid(uid);
        return true;
    }

    @Override
    public boolean batchUpdateStatus(List<String> uids, String orgId, Integer type) {
        List<String> uidList = new ArrayList<>();
        for(String uid:uids){
            if(uid!=null){
                uidList.add(uid.trim());
            }
        }
        if(CollectionUtils.isEmpty(uidList)){
            return false;
        }
        int num = mbUserOrgRelationMapper.batchUpdateStauts(uidList, orgId, type);
        return num > 0;
    }
    @Override
    public MbUserOrgRelation find(String orgId, String uid) {

        MbUserOrgRelation selectParam = new MbUserOrgRelation();
        selectParam.setOrgId(orgId);
        selectParam.setUid(uid==null?null:uid.trim());
//        selectParam.setIsDeleted(0);
        selectParam.setDeleteTime(new Date(0));
        return mbUserOrgRelationMapper.selectOne(selectParam);
    }

    @Override
    public List<MbUserOrgRelation> findByUid(String uid) {
        MbUserOrgRelation selectParam = new MbUserOrgRelation();
        selectParam.setUid(uid);
        selectParam.setDeleteTime(new Date(0));
        return mbUserOrgRelationMapper.select(selectParam);
    }

    @Override
    public List<MbUserOrgRelation> findByUids(List<String> uids) {
        if (CollectionUtils.isEmpty(uids)){
            return Collections.emptyList();
        }
        Example example = new Example(MbUserOrgRelation.class);
        example.createCriteria().andIn("uid", uids).andEqualTo("deleteTime", new Date(0));
        return mbUserOrgRelationMapper.selectByExample(example);
    }

    @Override
    public boolean batchSave(List<MbUserOrgRelation> needSaveList) {
        trimUid(needSaveList);
        int num = mbUserOrgRelationMapper.batchSave(needSaveList);
        return num > 0;
    }

    @Override
    public boolean save(MbUserOrgRelation mbUserOrgRelation) {
        trimUid(mbUserOrgRelation);
        return mbUserOrgRelationMapper.insertSelective(mbUserOrgRelation) > 0;
    }

    @Override
    public boolean setUpLeader(String orgId, List<String> uids) {
        int num = mbUserOrgRelationMapper.setUpLeader(orgId, uids, 1);
        try {
            MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
            for (String uid : uids) {
                MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
                if (mbOrgEmployeeInfo == null) {
                    continue;
                }
                // 查询人的证件信息
                List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(uids);
                Map<String, List<MbOrgUserIdcard>> userCardMap = MapUtil.newHashMap();
                if (CollUtil.isNotEmpty(userIdcards)) {
                    userCardMap = userIdcards.stream().sorted((a, b) -> b.getDatachangeLasttime().compareTo(a.getDatachangeLasttime())).collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
                }

                OrgPostLogVo orgEmployeeVo = new OrgPostLogVo();
                orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
                orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
                orgEmployeeVo.setPhone("+" + mbOrgEmployeeInfo.getAreaCode() + " " + mbOrgEmployeeInfo.getMobilePhone());
                List<MbOrgUserIdcard> idcards = userCardMap.get(mbOrgEmployeeInfo.getUid());
                if (CollUtil.isNotEmpty(idcards)) {
                    MbOrgUserIdcard mbOrgUserIdcard = idcards.get(0);
                    CardCodeEnum cardCodeEnum = CardCodeEnum.get(String.valueOf(mbOrgUserIdcard.getCardType()));
                    orgEmployeeVo.setCardType(cardCodeEnum.getDesc());
                    // 证件号加密
                    String encryptStr = encryptCardNo(mbOrgUserIdcard.getCardNo(), mbOrgUserIdcard.getCardType());
                    orgEmployeeVo.setCardNo(encryptStr);
                }
                // 是不是管理员
                GetUserRoleDetailRequest req = new GetUserRoleDetailRequest();
                req.setUid(mbOrgEmployeeInfo.getUid());
                req.setOrgId(mbOrgEmployeeInfo.getOrgId());
                GetUserRoleListResponse data = userService.getUserRoleDetail(req);
                List<GetUserRoleListInfo> userRoleListInfoList = data.getUserRoleListInfoList();
                if (CollUtil.isNotEmpty(userRoleListInfoList)) {
                    orgEmployeeVo.setIsMageger("是");
                } else {
                    orgEmployeeVo.setIsMageger("否");
                }
                if (mbOrgEmployeeInfo.getIsLeader() == null || mbOrgEmployeeInfo.getIsLeader() == false) {
                    orgEmployeeVo.setIsCharge("否");
                } else {
                    orgEmployeeVo.setIsCharge("是");
                }
                if (mbOrgInfo != null) {
                    orgEmployeeVo.setCompanyName(mbOrgInfo.getName());
                }

                UserOrgRelationStatusEnum byCode = UserOrgRelationStatusEnum.getByCode(mbOrgEmployeeInfo.getStatus() == null ? 1 : mbOrgEmployeeInfo.getStatus());
                orgEmployeeVo.setStatus(byCode.getDesc());

                // 职级
                if (mbOrgEmployeeInfo.getPostId() != null) {
                    MbPostInfo mbPostInfo = postService.find(mbOrgEmployeeInfo.getPostId());
                    orgEmployeeVo.setRank(mbPostInfo.getName());
                }
                OrgPostLogVo orgPostLogVo = JsonUtils.convert(orgEmployeeVo, OrgPostLogVo.class);
                orgPostLogVo.setIsCharge("是");
                updateOperateLog(orgEmployeeVo, orgPostLogVo);
            }
        } catch (Exception e) {
            log.error("人员信息管理设为负责人异常，原因:{}", e.getMessage(), e);
        }
        return num > 0;
    }

    @Override
    public boolean cleanPostIdByPostId(Long postId) {
        mbUserOrgRelationMapper.cleanPostIdByPostId(postId);
        return true;
    }

    @Override
    public boolean cleanPostIdByUidAndOrgId(String uid, String orgId) {
        return mbUserOrgRelationMapper.cleanPostIdByUidAndOrgId(uid, orgId) == 1;
    }

    @Override
    public boolean setPostIdByUidAndOrgId(String uid, String orgId, Long postId) {
        return mbUserOrgRelationMapper.setPostIdByUidAndOrgId(uid, orgId, postId) == 1;
    }

    @Override
    public List<MbUserOrgRelation> listByUid(String uid) {

        if (StringUtils.isEmpty(uid)) {
            return new ArrayList<>();
        }

        MbUserOrgRelation selectParam = new MbUserOrgRelation();
        selectParam.setUid(uid);
//        selectParam.setIsDeleted(0);
        selectParam.setDeleteTime(new Date(0));
        return mbUserOrgRelationMapper.select(selectParam);
    }

    @Override
    public boolean batchUpdatePostByUidAndOrgId(Long postId, List<String> uids, String orgId) {
        List<String> uidList = new ArrayList<>();
        try {
            MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
            for (String uid : uids) {
                if(uid!=null){
                    uidList.add(uid.trim());
                }
                MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
                if (mbOrgEmployeeInfo == null) {
                    continue;
                }
                MbUserOrgRelation mbUserOrgRelation;
                OrgPostLogVo orgPostLogVo = null;
                // 查询人的证件信息
                List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(uids);
                Map<String, List<MbOrgUserIdcard>> userCardMap = MapUtil.newHashMap();
                if (CollUtil.isNotEmpty(userIdcards)) {
                    userCardMap = userIdcards.stream().sorted((a, b) -> b.getDatachangeLasttime().compareTo(a.getDatachangeLasttime())).collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
                }
                OrgPostLogVo orgEmployeeVo = new OrgPostLogVo();
                orgEmployeeVo.setId(mbOrgEmployeeInfo.getId());
                orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
                orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
                orgEmployeeVo.setPhone("+" + mbOrgEmployeeInfo.getAreaCode() + " " + mbOrgEmployeeInfo.getMobilePhone());
                List<MbOrgUserIdcard> idcards = userCardMap.get(mbOrgEmployeeInfo.getUid());
                if (CollUtil.isNotEmpty(idcards)) {
                    MbOrgUserIdcard mbOrgUserIdcard = idcards.get(0);
                    CardCodeEnum cardCodeEnum = CardCodeEnum.get(String.valueOf(mbOrgUserIdcard.getCardType()));
                    orgEmployeeVo.setCardType(cardCodeEnum.getDesc());
                    // 证件号加密
                    String encryptStr = encryptCardNo(mbOrgUserIdcard.getCardNo(), mbOrgUserIdcard.getCardType());
                    orgEmployeeVo.setCardNo(encryptStr);
                }
                // 是不是管理员
                GetUserRoleDetailRequest req = new GetUserRoleDetailRequest();
                req.setUid(mbOrgEmployeeInfo.getUid());
                req.setOrgId(mbOrgEmployeeInfo.getOrgId());
                GetUserRoleListResponse data = userService.getUserRoleDetail(req);
                List<GetUserRoleListInfo> userRoleListInfoList = data.getUserRoleListInfoList();
                if (CollUtil.isNotEmpty(userRoleListInfoList)) {
                    orgEmployeeVo.setIsMageger("是");
                } else {
                    orgEmployeeVo.setIsMageger("否");
                }
                if (mbOrgEmployeeInfo.getIsLeader() == null || mbOrgEmployeeInfo.getIsLeader() == false) {
                    orgEmployeeVo.setIsCharge("否");
                } else {
                    orgEmployeeVo.setIsCharge("是");
                }
                if (mbOrgInfo != null) {
                    orgEmployeeVo.setCompanyName(mbOrgInfo.getName());
                }
                UserOrgRelationStatusEnum byCode = UserOrgRelationStatusEnum.getByCode(mbOrgEmployeeInfo.getStatus() == null ? 1 : mbOrgEmployeeInfo.getStatus());
                orgEmployeeVo.setStatus(byCode.getDesc());
                orgPostLogVo = JsonUtils.convert(orgEmployeeVo, OrgPostLogVo.class);
                MbPostInfo mbPostInfo = postService.find(postId);
                if (mbPostInfo != null) {
                    orgEmployeeVo.setRank(mbPostInfo.getName());
                }
                mbUserOrgRelation = new MbUserOrgRelation();
                mbUserOrgRelation.setOrgId(orgId);
                mbUserOrgRelation.setUid(uid);
                List<MbUserOrgRelation> select = mbUserOrgRelationMapper.select(mbUserOrgRelation);
                // 职级
                if (!CollectionUtils.isEmpty(select)) {
                    MbUserOrgRelation mbRelation = select.get(0);
                    Long relationPostId = mbRelation.getPostId();
                    if (relationPostId != null) {
                        mbPostInfo = postService.find(relationPostId);
                        orgPostLogVo.setRank(mbPostInfo.getName());
                    }
                }
                updateOperateLog(orgPostLogVo, orgEmployeeVo);
            }
        } catch (Exception e) {
            log.error("修改人员信息操作日志失败，原因:{}", e.getMessage(), e);
        }

        int num = mbUserOrgRelationMapper.batchUpdatePostByUidAndOrgId(postId, uidList, orgId);

        if (num > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean cancelSetUpLeader(String orgId, List<String> uids) {
        int num = mbUserOrgRelationMapper.setUpLeader(orgId, uids, 0);
        return num > 0;
    }

    @Override
    public List<MbUserOrgRelation> listLeader(String orgId) {

        if (StringUtils.isEmpty(orgId)) {
            return new ArrayList<>();
        }

        MbUserOrgRelation selectParam = new MbUserOrgRelation();
        selectParam.setOrgId(orgId);
        selectParam.setIsLeader(1);
//        selectParam.setIsDeleted(0);
        selectParam.setDeleteTime(new Date(0));
        selectParam.setStatus(1);
        return mbUserOrgRelationMapper.select(selectParam);
    }

    @Override
    public List<MbUserOrgRelation> listAllLeaders() {
        MbUserOrgRelation selectParam = new MbUserOrgRelation();
        selectParam.setIsLeader(1);
        selectParam.setDeleteTime(new Date(0));
        selectParam.setStatus(1);
        return mbUserOrgRelationMapper.select(selectParam);
    }

    @Override
    public boolean deleteByUid(String uid) {
        return mbUserOrgRelationMapper.deleteByUid(uid) > 0;
    }

    @Override
    public boolean batchClearLeader(List<String> id, String orgId) {
        return mbUserOrgRelationMapper.batchClearLeader(id, orgId) > 0;
    }

    @Override
    public boolean update(MbUserOrgRelation mbUserOrgRelation) {
        trimUid(mbUserOrgRelation);
        return mbUserOrgRelationMapper.updateByPrimaryKeySelective(mbUserOrgRelation) > 0;
    }

    @Override
    public int countNormalUserByPostId(long postId) {
        return mbUserOrgRelationMapper.selectCount(new MbUserOrgRelation() {{
            setPostId(postId);
//            setIsDeleted(0);
            setDeleteTime(new Date(0));
            setStatus(1);
        }});
    }

    @Override
    public MbUserOrgRelation get(MbUserOrgRelation mbUserOrgRelation) {
        return mbUserOrgRelationMapper.selectOne(mbUserOrgRelation);
    }

    @Override
    public List<MbOrgEmployeeInfo> listByPk(List<OrgUserInfoPk> pkList) {
        return orgEmployeeMapper.listByPk(pkList);
    }

    @Override
    public int countEmployee(Integer status, List<String> orgIds) {
        return mbUserOrgRelationMapper.countEmployee(status, orgIds);
    }

    @Override
    public List<MbUserOrgRelation> listByUids(List<String> employeeUidList) {
        if (CollectionUtils.isEmpty(employeeUidList)) {
            return null;
        }
        return mbUserOrgRelationMapper.listByUids(employeeUidList);
    }

    @Override
    public List<MbUserOrgRelation> listByUids() {
        return mbUserOrgRelationMapper.listByUids(null);
    }

    @Override
    public List<ListUserOrgRelationForLoginResponse> listUserOrgRelationForLogin(ListUserOrgRelationForLoginRequest request) {
        String uid = request.getUid();
        List<MbUserOrgRelation> userOrgRelationList = this.listByUid(uid);
        List<ListUserOrgRelationForLoginResponse> returnList = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(userOrgRelationList)) {
            // 查询所有组织结构信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
            Map<String, MbOrgInfo> orgMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, p -> p));
            // 查询用户的信息
            List<String> uids = userOrgRelationList.stream().map(MbUserOrgRelation::getUid).collect(Collectors.toList());
            List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByUids(uids);
            Map<String, MbOrgEmployeeInfo> userMap = employeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
            // 过滤出审核中和审核过的数据
            userOrgRelationList = userOrgRelationList.stream().filter(p -> p.getStatus().equals(1) || p.getStatus().equals(2)).collect(Collectors.toList());
            for (MbUserOrgRelation mbUserOrgRelation : userOrgRelationList) {
                ListUserOrgRelationForLoginResponse info = new ListUserOrgRelationForLoginResponse();
                String orgId = mbUserOrgRelation.getOrgId();
                // 查询身份所在部门是否禁用，如果禁用，不展示
                MbOrgInfo orgInfo = orgMap.get(orgId);
                if (orgInfo == null) {
                    continue;
                }
                if (orgInfo.getValid().equals(CommonConst.FALSE)) {
                    continue;
                }
                info.setOrgId(orgId);
                info.setOrgName(orgInfo.getName());
                // 如果是部门，接着找到末级子公司
                if (orgInfo.getOrgType().equals(OrgTypeEnum.D.getCode())) {
                    MbOrgInfo recentCompanyInfo = OrganizationUtil.findRecentCompanyInfo(orgId, orgMap);
                    info.setCorpId(recentCompanyInfo.getOrgId());
                    info.setCorpName(recentCompanyInfo.getName());
                } else {
                    // 如果当前是公司，直接放入当前公司的信息
                    info.setCorpId(orgInfo.getOrgId());
                    info.setCorpName(orgInfo.getName());
                }
                info.setUid(uid);
                if (MapUtil.isNotEmpty(userMap)) {
                    MbOrgEmployeeInfo userInfo = userMap.get(uid);
                    if (userInfo != null) {
                        info.setUserName(userInfo.getName());
                        info.setEmail(userInfo.getEmail());
                    }
                }
                //查询出当前用户得角色ID
                info.setRoleId(
                        Optional.ofNullable(userRoleMapper.findByUidAndOrgId(uid, orgId)).orElse(new ArrayList<>()).stream().map(MbUserRole::getRoleId).collect(Collectors.toList())
                );

                if (mbUserOrgRelation.getStatus().equals(UserOrgRelationStatusEnum.VERIFY.getStatus())) {
                    info.setApprovalStatus(0);
                } else if (mbUserOrgRelation.getStatus().equals(UserOrgRelationStatusEnum.NORMAL.getStatus())) {
                    info.setApprovalStatus(1);
                }
                returnList.add(info);
            }
        }
        return returnList;
    }

    @Override
    public boolean batchUpdateUserOrgRelation(TransferEmployeeOrgInfoVo request) {
        request.getEmployeeOrgInfoList().forEach(item -> {
            mbUserOrgRelationMapper.updateUserOrgRelation(request.getNewOrgId(), item.getOldOrgId(), item.getUid()==null?null:item.getUid().trim(), false, item.getPostId());
        });
        return true;
    }

    @Override
    public boolean deleteUserOrgRelation(TransferEmployeeOrgInfoVo request) {
        request.getEmployeeOrgInfoList().forEach(item -> {
            mbUserOrgRelationMapper.deleteByOrgIdAndUid(item.getUid(), item.getOldOrgId());
        });
        return true;
    }

    @Override
    public boolean updatePostIdById(Long postId, Long id) {
        mbUserOrgRelationMapper.updatePostIdById(postId, id);
        return true;
    }

    @Override
    public boolean deleteByUidAndOrgIdList(List<MbUserOrgRelation> mbUserOrgRelationList) {
        if (CollectionUtils.isEmpty(mbUserOrgRelationList)){
            return false;
        }
        return mbUserOrgRelationMapper.deleteByUidAndOrgIdList(mbUserOrgRelationList) >0;
    }

    @Override
    public boolean insertList(List<MbUserOrgRelation> mbUserOrgRelationList) {
        if (CollectionUtils.isEmpty(mbUserOrgRelationList)){
            return false;
        }
        trimUid(mbUserOrgRelationList);
        return mbUserOrgRelationMapper.insertList(mbUserOrgRelationList) >0;
    }

    @Override
    public boolean updateByRecord(MbUserOrgRelation record) {
        Example example = new Example(MbUserOrgRelation.class);
        trimUid(record);
        example.createCriteria()
                .andEqualTo("uid", record.getUid()).andEqualTo("deleteTime", new Date(0));
        return mbUserOrgRelationMapper.updateByExampleSelective(record, example) > 0;
    }

    private OrganizationChangeHistoryModel buildOrganizationChangeHistory(String uid, String orgId){
        List<MbOrgEmployeeInfo> mbOrgEmployeeInfoList = organizationEmployeeService.selectByUid(uid);
        log.info("mbOrgEmployeeInfoList:{}", JsonUtils.toJsonString(mbOrgEmployeeInfoList));
        if (CollectionUtils.isEmpty(mbOrgEmployeeInfoList)){
            return null;
        }
        OrganizationChangeHistoryModel model = new OrganizationChangeHistoryModel();
        model.setCurrentOrgId(null);
        model.setEmployeeId(mbOrgEmployeeInfoList.get(0).getId());
        model.setBeforeOrgId(orgId);
        model.setOperateType(EmployeeOperateEnum.DELETE.name());
        return model;
    }

    private void trimUid(MbUserOrgRelation orgRelation){
        if(orgRelation==null){
            return;
        }
        if(orgRelation.getUid()!=null){
            orgRelation.setUid(orgRelation.getUid().trim());
        }
        if(orgRelation.getOrgId()!=null){
            orgRelation.setOrgId(orgRelation.getOrgId().trim());
        }
    }

    private void trimUid(List<MbUserOrgRelation> orgRelationList){
        if(CollectionUtils.isEmpty(orgRelationList)){
            return;
        }
        for(MbUserOrgRelation relation:orgRelationList){
            if(relation==null){
                continue;
            }
            trimUid(relation);
        }
    }
}
